import React, { Component } from 'react'
import axios from "axios"
import { connect } from "react-redux"
import { Vote } from "../../../types/vote"
import VoteItem from "../../../components/voteitem"
interface Iprops {
    initList: (list: Vote[]) => void,
    votelist: Vote[]
}
export class Home extends Component<Iprops, {}> {
    componentDidMount() {
        if (this.props.votelist.length <= 0) {
            axios.get('/api/votelist').then(res => {
                this.props.initList(res.data.votelist)
            })
        }
    }
    render() {
        let { votelist } = this.props
        return (
            <div>
                {
                    votelist.length && votelist.map((item: Vote) => <VoteItem key={item.vid} item={item}></VoteItem>)
                }
            </div>
        )
    }
}
let stateMapToProps = (state: any) => {
    return {
        votelist: state.vote.votelist
    }
}
let dispatchMapToProps = (dispatch: any) => {
    return {
        initList(list: Vote[]) {
            dispatch({ type: "INIT_VOTELIST", list })
        }
    }
}
export default connect(stateMapToProps, dispatchMapToProps)(Home)
